package xyz.ibenben.zhongdian.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.entity.OtherRightDigest;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.form.OtherRightDigestForm;
import xyz.ibenben.zhongdian.system.service.OtherRightDigestService;
import xyz.ibenben.zhongdian.system.service.PropertyOwnershipCertificateService;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 他项权利摘要控制类
 * 提供了一些基本的服务，如初始化、获取他项权利摘要列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Controller
@SessionAttributes("otherRightDigestForm")
@RequestMapping("/otherRightDigest")
public class OtherRightDigestController extends BaseController {
    /**
     * 实体名称
     */
    private static final String ENTITYNAME = "otherRightDigest";
    /**
     * 重定向页面2
     */
    private static final String REDIRECT2 = "redirect:/" + ENTITYNAME + "/getAll?ownerId=%s";

    @Resource
    private OtherRightDigestService otherRightDigestService;
    @Resource
    private PropertyOwnershipCertificateService propertyOwnershipCertificateService;

    /**
     * 数据转换
     *
     * @param binder 转换器
     */
    @InitBinder
    public void binder(WebDataBinder binder) {
        //转换日期
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // CustomDateEditor为自定义日期编辑器
        binder.registerCustomEditor(Date.class, "setDate", new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(Date.class, "dateLimit", new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(Date.class, "logoutDate", new CustomDateEditor(dateFormat, true));
    }

    /**
     * 初始化
     *
     * @param map                  参数
     * @param otherRightDigestForm 条件参数
     */
    @ModelAttribute
    public void init(Model map, @ModelAttribute OtherRightDigestForm otherRightDigestForm,
                     @RequestParam(value = "ownerId", required = false) Long ownerId, HttpSession session) {
        OtherRightDigestForm newOtherRightDigestForm = new OtherRightDigestForm();
        if (otherRightDigestForm != null) {
            newOtherRightDigestForm = otherRightDigestForm;
            if (ownerId != null) {
                newOtherRightDigestForm.setOwnerId(ownerId);
            }
        }
        SysUser user = (SysUser) session.getAttribute(Constants.SESSION);
        if (user != null && user.getSysRole() != null) {
            newOtherRightDigestForm.setCompanyId(user.getSysRole().getCompanyId());
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newOtherRightDigestForm);
    }

    /**
     * 获取他项权利摘要列表
     *
     * @param map                  参数
     * @param otherRightDigestForm 条件参数
     * @param ownerId              拥有者主键
     * @return 页面
     */
    @RequestMapping(value = "/getAll")
    @SystemControllerLog(description = "获取他项权利摘要列表")
    public String getAll(Model map, @ModelAttribute OtherRightDigestForm otherRightDigestForm,
                         @RequestParam(value = "ownerId", required = false) Long ownerId) {
        if (ownerId != null) {
            otherRightDigestForm.setOwnerId(ownerId);
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), otherRightDigestForm);
        Page<OtherRightDigest> page = new Page<>(otherRightDigestForm.getPageIndex(), otherRightDigestForm.getPageSize());
        IPage<OtherRightDigest> result = otherRightDigestService.findAll(page, otherRightDigestForm);
        map.addAttribute(Constants.PI, result);
        return String.format(Constants.LISTPAGE, ENTITYNAME);
    }

    /**
     * 删除他项权利摘要记录
     *
     * @param id                   他项权利摘要主键
     * @param otherRightDigestForm 条件参数
     * @return 页面
     */
    @RequestMapping(value = "/delete")
    @SystemControllerLog(description = "删除他项权利摘要记录")
    public String delete(@RequestParam("id") Long id,
                         @ModelAttribute OtherRightDigestForm otherRightDigestForm, SessionStatus status) {
        otherRightDigestService.removeById(id);
        status.setComplete();
        if (otherRightDigestForm.getOwnerId() != null) {
            return String.format(REDIRECT2, otherRightDigestForm.getOwnerId());
        }
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 删除他项权利摘要列表
     *
     * @param otherRightDigestForm 条件参数
     * @return 页面
     */
    @RequestMapping("/deleteAll")
    @SystemControllerLog(description = "删除他项权利摘要列表")
    public String deleteAll(@ModelAttribute OtherRightDigestForm otherRightDigestForm,
                            SessionStatus status) {
        if (otherRightDigestForm.getSelectIds() != null) {
            String[] ids = otherRightDigestForm.getSelectIds().split(Constants.COMMA);
            for (String id : ids) {
                otherRightDigestService.removeById(Long.parseLong(id));
            }
        }
        status.setComplete();
        if (otherRightDigestForm.getOwnerId() != null) {
            return String.format(REDIRECT2, otherRightDigestForm.getOwnerId());
        }
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 打开他项权利摘要添加页面
     *
     * @param map                  参数
     * @param otherRightDigestForm 条件参数
     * @return 页面
     */
    @GetMapping("/add")
    @SystemControllerLog(description = "打开他项权利摘要添加页面")
    public String openAddPage(Model map, @ModelAttribute OtherRightDigestForm otherRightDigestForm) {
        OtherRightDigest otherRightDigest = new OtherRightDigest();
        super.setPropertyOwnershipCertificate(map, otherRightDigestForm.getOwnerId(),
                otherRightDigest, propertyOwnershipCertificateService);
        map.addAttribute(ENTITYNAME, otherRightDigest);
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 保存他项权利摘要添加记录
     *
     * @param otherRightDigest 实体
     * @param bindingResult    校验
     * @return 页面
     */
    @PostMapping("/add")
    @SystemControllerLog(description = "保存他项权利摘要添加记录")
    public String postAddMessage(@Valid @ModelAttribute(ENTITYNAME) OtherRightDigest otherRightDigest,
                                 BindingResult bindingResult, SessionStatus status) {
        if (!bindingResult.hasErrors()) {
            otherRightDigestService.save(otherRightDigest);
            if (otherRightDigest.isFromOwnerId()) {
                return String.format(REDIRECT2, otherRightDigest.getOwnerId());
            }
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        }
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 打开他项权利摘要修改页面
     *
     * @param map                  参数
     * @param id                   他项权利摘要主键
     * @param otherRightDigestForm 条件参数
     * @return 页面
     */
    @GetMapping("/edit")
    @SystemControllerLog(description = "打开他项权利摘要修改页面")
    public String openEditPage(Model map, @RequestParam("id") Long id,
                               @ModelAttribute OtherRightDigestForm otherRightDigestForm) {
        OtherRightDigest info = otherRightDigestService.getById(id);
        if (otherRightDigestForm.getOwnerId() != null) {
            info.setFromOwnerId(true);
        }
        map.addAttribute(ENTITYNAME, info);
        return String.format(Constants.EDITPAGE, ENTITYNAME);
    }

    /**
     * 更新他项权利摘要修改记录
     *
     * @param otherRightDigest 实体
     * @param bindingResult    校验
     * @return 页面
     */
    @PostMapping("/edit")
    @SystemControllerLog(description = "更新他项权利摘要修改记录")
    public String postEditMessage(@Valid @ModelAttribute(ENTITYNAME) OtherRightDigest otherRightDigest,
                                  BindingResult bindingResult, SessionStatus status) {
        if (!bindingResult.hasErrors()) {
            otherRightDigestService.updateById(otherRightDigest);
            status.setComplete();
            if (otherRightDigest.isFromOwnerId()) {
                return String.format(REDIRECT2, otherRightDigest.getOwnerId());
            }
            return String.format(Constants.REDIRECT, ENTITYNAME);
        }
        return String.format(Constants.EDITPAGE, ENTITYNAME);
    }

    /**
     * 浏览他项权利摘要记录
     *
     * @param map                  参数
     * @param id                   主键
     * @param otherRightDigestForm 条件参数
     * @return 页面
     */
    @GetMapping("/view")
    @SystemControllerLog(description = "浏览他项权利摘要记录")
    public String openViewPage(Model map, @RequestParam("id") Long id,
                               @ModelAttribute OtherRightDigestForm otherRightDigestForm) {
        map.addAttribute(ENTITYNAME, otherRightDigestService.getById(id));
        return String.format(Constants.VIEWPAGE, ENTITYNAME);
    }

}

